package com.gmzg.gmzgnews.live.view;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.gmzg.gmzgnews.R;
import com.gmzg.gmzgnews.live.adapter.LiveFragmentAdapter;
import com.gmzg.gmzgnews.live.adapter.PicturePageAdapter;
import com.gmzg.gmzgnews.live.model.LiveModel;
import com.gmzg.gmzgnews.live.services.LiveHotService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class HotTopFragmentWithDB extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,Runnable {

    ArrayList<LiveModel.Data.DataBean> mItems;
    LiveFragmentAdapter mAdapter;
    private int currentIndex = 1500;

    private Handler mHandler;

    @BindView(R.id.hot_list)
    RecyclerView mHotList;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private LiveHotService mLiveHotService;


    public HotTopFragmentWithDB() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("ddddddddd", "onCreate: ");
//        注册EventBus事件,接受点击时传过来的对象
        EventBus.getDefault().register(this);

        mItems = new ArrayList<>();

        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://ic.snssdk.com/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build();
        mLiveHotService = retrofit.create(LiveHotService.class);

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("ddddddddd", "onResume: ");
//        mItems.clear();
//        reloadLiveHotList();

        //启动广告轮播线程
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public String getFragmentTitle() {
        return "热门";
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d("ddddddddd", "onAttach: ");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_hot_top, container, false);
        ButterKnife.bind(this, ret);
        Log.d("ddddddddd", "onCreateView: ");

        //添加刷新监听事件
        mSwipeRefreshLayout.setOnRefreshListener(this);

        if (mHotList != null) {
            //布局管理器，能够对Item进行排版
            RecyclerView.LayoutManager lm =
                    new LinearLayoutManager(
                            getContext(),
                            LinearLayoutManager.VERTICAL,
                            false);

            mHotList.setLayoutManager(lm);

        }
        mAdapter = new LiveFragmentAdapter(getContext(), mItems, mHotList);
//        View headView= LayoutInflater.from(getContext()).inflate(R.layout.live_hot_headview,mHotList,false);

        //添加广告轮播
        ViewPager headView= (ViewPager)LayoutInflater.from(getContext()).inflate(R.layout.live_hot_ad,mHotList,false);
        List<Integer> images = new ArrayList<>();
        images.add(R.drawable.live_hot_ad1);
        images.add(R.drawable.live_hot_ad2);
        images.add(R.drawable.live_hot_ad3);
        images.add(R.drawable.live_hot_ad4);
        PicturePageAdapter pageAdapter = new PicturePageAdapter(getContext(), images);
        headView.setAdapter(pageAdapter);
        mHandler = new AdHandler(headView);
        //为RecyclerView添加头布局
        mAdapter.addHeadView(headView);
        //监听是否滑动到最下边，到达加载更多数据
        mAdapter.setOnLoadMoreListener(new LiveFragmentAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        mHotList.setAdapter(mAdapter);

        reloadLiveHotList();
        return ret;
    }

    @Override
    public void run() {
        try {
            while (true) {
                currentIndex++;
                if (currentIndex >= 3000) {
                    currentIndex = 1500;
                }
                Message message = mHandler.obtainMessage(998);
                message.arg1 = currentIndex;
                mHandler.sendMessage(message);
                Thread.sleep(5000);
            }
        }catch (InterruptedException ex){
            ex.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        Log.d("ddddddddd", "onDestroyView: ");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Log.d("ddddddddd", "onDestroy: ");
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        Log.d("ddddddddd", "onDetach: ");
        super.onDetach();
    }

    @Subscribe
    public void onReceiveHotDetail(LiveModel.Data.DataBean.GroupBean dataBean) {
        Toast.makeText(getContext(), "点击了" + dataBean.getTitle(), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(getContext(), HotDetailActivity.class);
        intent.putExtra("groupBean", dataBean);
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        reloadLiveHotList();
    }

    private void reloadLiveHotList() {
        Observable<LiveModel> observable = mLiveHotService.getLiveModel();
        observable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new LiveModelObserver());
    }

    private class LiveModelObserver implements Observer<LiveModel> {
        @Override
        public void onCompleted() {
            Log.d("ddddddddd", "onCompleted: ");

        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
        }

        @Override
        public void onNext(LiveModel model) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
            String tip = model.getData().getTip();
            Log.d("ddddddd", "call: " + tip);
            mItems.clear();
            List<LiveModel.Data.DataBean> dataBeanList = model.getData().getData();
            mItems.addAll(dataBeanList);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void loadMore() {
        Observable<LiveModel> observable = mLiveHotService.getLiveModel();
        observable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new MoreLiveModelObserver());
    }
    private class MoreLiveModelObserver implements Observer<LiveModel> {
        @Override
        public void onCompleted() {
            Log.d("ddddddddd", "onCompleted: ");

        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
        }

        @Override
        public void onNext(LiveModel model) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
            }
            String tip = model.getData().getTip();
            Log.d("ddddddd", "call: " + tip);
            List<LiveModel.Data.DataBean> dataBeanList = model.getData().getData();
            mItems.addAll(dataBeanList);
            mAdapter.notifyDataSetChanged();
        }
    }

    private static class AdHandler extends Handler{

        private ViewPager mPager;

        public AdHandler(ViewPager pager) {
            mPager = pager;
        }

        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if(what == 998){
                int index = msg.arg1;
                mPager.setCurrentItem(index);
            }
        }
    }
}
